package com.example.springbatchdemo.config;


import com.example.springbatchdemo.config.listener.MyChunkLinster;
import com.example.springbatchdemo.config.listener.MyJobListener;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.support.ListItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.List;

/**
 * @Classname ListenerDemo
 * @Description TODO
 * @Date 2020/9/19 14:32
 * @Created by kevin
 */
@Configuration
public class ListenerDemo {

    @Autowired
    private JobBuilderFactory jobBuilderFactory;
    @Autowired
    private StepBuilderFactory stepBuilderFactory;
    @Autowired
    private MyJobListener myJobListener;
    @Autowired
    private MyChunkLinster myChunkLinster;

    @Bean
    public Job listenerDemoJob() {
        return jobBuilderFactory.get("listenerDemoJob")
                .start(listenerDemostep())
                .listener(myJobListener)
                .build();
    }

    @Bean
    public Step listenerDemostep() {

        return stepBuilderFactory.get("listenerDemostep")
                .<String, String>chunk(2)
                .faultTolerant()
                .listener(myChunkLinster)
                .reader(read())
                .writer(write())
                .build();
    }

    @Bean
    public ItemWriter<String> write() {


        return new ItemWriter<String>() {
            @Override
            public void write( List<? extends String> list ) throws Exception {
                list.stream().forEach(System.out::println);
            }
        };
    }

    @Bean
    public ItemReader<String> read() {

        return new ListItemReader<>(Arrays.asList(
                "张三", "李四", "王五"
        ));
    }

}
